package org.example.rowing.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.util.BaseController;
import org.example.rowing.controller.util.NavigationUtil;
import org.example.rowing.domain.Event;
import org.example.rowing.domain.Team;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.enums.GenderEnum;
import org.example.rowing.service.EventInfoService;
import org.example.rowing.service.TeamInfoService;
import org.example.rowing.vo.AthleteVO;
import org.example.rowing.vo.EventVO;
import org.example.rowing.vo.TeamVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Controller
@Slf4j
public class CKTeamInfoController extends BaseController {

    @FXML
    public Label importAthleteStatusLabel;
    @FXML
    public Label importTeamStatusLabel;
    @FXML
    public ComboBox<String> boatTypeComboBox;
    @FXML
    public ComboBox<String> boatTypeComboBox1;
    @FXML
    public TextField searchTextField1;
    @FXML
    public TextField searchTextField4;
    @FXML
    public TextField searchTextField5;
    @FXML
    public ComboBox<EventVO> searchField;

    @FXML
    private VBox sideNav;
    @FXML
    public TableView<TeamVO> teamTable;
    @FXML
    public TableView<AthleteVO> athleteTable;
    private ObservableList<TeamVO> teamList;
    private ObservableList<AthleteVO> athleteList;
    @FXML
    private Button addCKTeamButton;
    @FXML
    private Button addCKAthleteButton;
    @FXML
    private Button btnCKTeams;

    @FXML
    public TableColumn<TeamVO, String> idColumn;
    @FXML
    private TableColumn<TeamVO, String> nameColumn;
    @FXML
    private TableColumn<TeamVO, String> eventColumn;
    @FXML
    private TableColumn<TeamVO, String> countryColumn;
    @FXML
    private TableColumn<TeamVO, String> leaderColumn;
    @FXML
    private TableColumn<TeamVO, String> infoColumn;
    @FXML
    private TableColumn<TeamVO, Void> operationColumn;

    @FXML
    private TableColumn<AthleteVO, String> athleteNameColumn;
    @FXML
    private TableColumn<AthleteVO, String> genderColumn;
    @FXML
    private TableColumn<AthleteVO, String> teamNameColumn;
    @FXML
    public TableColumn<AthleteVO, String> teamIdColumn;
    @FXML
    public TableColumn<AthleteVO, String> categoryColumn;
    @FXML
    private TableColumn<AthleteVO, String> birthdateColumn;
    @FXML
    private TableColumn<AthleteVO, Void> athleteOperationColumn;

    @Autowired
    private TeamInfoService teamInfoService;
    @Autowired
    private EventInfoService eventInfoService;

    @Override
    protected Button getButton() {
        return btnCKTeams;
    }

    @Override
    public void initialize() {
        super.initialize();

        // 设置表格列
        idColumn.setCellValueFactory(cellData -> new SimpleStringProperty(String.valueOf(cellData.getValue().getId())));
        nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
        eventColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getEventVO().getName()));
        countryColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getCountry()));
        leaderColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getCoachName()));
        infoColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getInfo()));

        athleteNameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
        genderColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getGenderEnum().getDisplayName()));
        teamNameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getTeam().getName()));
        teamIdColumn.setCellValueFactory(cellData -> new SimpleStringProperty(String.valueOf(cellData.getValue().getTeam().getId())));
        categoryColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getCategory()));
        birthdateColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getBirthDate()));

        // 设置操作列（修改、删除按钮）
        operationColumn.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    Button modifyButton = new Button("修改");
                    modifyButton.setOnAction(event -> handleModifyEvent(getTableRow().getItem(), null));

                    Button deleteButton = new Button("删除");
                    deleteButton.setOnAction(event -> handleDeleteEvent(getTableRow().getItem(), null));

                    HBox hBox = new HBox(modifyButton, deleteButton);
                    setGraphic(hBox);
                }
            }
        });
        athleteOperationColumn.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    Button modifyButton = new Button("修改");
                    modifyButton.setOnAction(event -> handleModifyEvent(null, getTableRow().getItem()));

                    Button deleteButton = new Button("删除");
                    deleteButton.setOnAction(event -> handleDeleteEvent(null, getTableRow().getItem()));

                    HBox hBox = new HBox(modifyButton, deleteButton);
                    setGraphic(hBox);
                }
            }
        });

        // 设置转换器，使下拉框只显示 eventName
        searchField.setConverter(new StringConverter<EventVO>() {
            @Override
            public String toString(EventVO event) {
                return event == null ? "" : event.getName();
            }
            @Override
            public EventVO fromString(String string) {
                // 一般不需要转换回对象，可返回 null 或自行实现
                return null;
            }
        });

        // 初始化赛事列表（默认展示一些数据）
        // 级联选择
        List<String> boatTypes = List.of("皮艇", "划艇");
        boatTypeComboBox.setItems(FXCollections.observableArrayList(boatTypes));

        boatTypeComboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                List<EventVO> eventVOS = eventInfoService.showEventsByType(BoatTypeEnum.fromDisplayName(newValue));
                searchField.setItems(FXCollections.observableArrayList(eventVOS));
                // 自动选中第一个项目（如果存在）
                if (!eventVOS.isEmpty()) {
                    searchField.getSelectionModel().select(0);
                }
            }
        });
        // 为下拉框添加监听器，用户选择其他赛事时更新表格数据
        searchField.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                updateTableForEvent(newValue);
            }
        });
        // 若需要在初始时就加载数据，可以先选中第一个赛事类型
        boatTypeComboBox.getSelectionModel().select(0);

        // 选手列表
        boatTypeComboBox1.setItems(FXCollections.observableArrayList(boatTypes));
        // 默认选中第一个
        boatTypeComboBox1.getSelectionModel().select(0);
        updateAthleteTableForBoatType(boatTypeComboBox1.getSelectionModel().getSelectedItem());
        // 为下拉框添加监听器，用户选择其他赛事时更新表格数据
        boatTypeComboBox1.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                updateAthleteTableForBoatType(newValue);
            }
        });
    }

    private void updateAthleteTableForBoatType(String boatType) {
        // 将过滤后的列表更新到表格
        athleteList = FXCollections.observableArrayList(teamInfoService.showAthletesByBoatType(BoatTypeEnum.fromDisplayName(boatType)));
        athleteTable.setItems(athleteList);
        athleteTable.refresh();
    }

    private void updateTableForEvent(EventVO eventVO) {
        // 将过滤后的列表更新到表格
        teamList = FXCollections.observableArrayList(teamInfoService.showTeamsByEventId(eventVO.getId()));
        teamTable.setItems(teamList);
        teamTable.refresh();
    }

    @FXML
    private void handleNavButtonClick(ActionEvent event) throws IOException {
        log.info("当前触发事件为：{}",event);
        Button clickedButton = (Button) sideNav.getScene().getFocusOwner();
        NavigationUtil.navigateToScene(
                event,
                NavigationUtil.viewMap.get(clickedButton.getId()),
                "皮划艇管理");
    }

    // 添加赛事事件
    @FXML
    private void handleAddTeam() {
        // 打开添加赛事界面的逻辑
        log.info("点击添加队伍按钮");
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(addCKTeamButton.getId()),
                "添加队伍",
                addCKTeamButton.getScene().getWindow(),
                controller -> {
                    if (controller instanceof UpdateCKTeamController) {
                        ((UpdateCKTeamController) controller).initialize(null);
                    }
                }
        );
        // 重新显示所有赛事
        teamList.setAll(teamInfoService.showTeamsByEventId(searchField.getSelectionModel().getSelectedItem().getId()));
        teamTable.refresh();
    }

    @FXML
    private void handleAddAthlete() {
        // 打开添加赛事界面的逻辑
        log.info("点击添加成员按钮");
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(addCKAthleteButton.getId()),
                "添加选手",
                addCKAthleteButton.getScene().getWindow(),
                controller -> {
                    if (controller instanceof UpdateCKAthleteController) {
                        ((UpdateCKAthleteController) controller).initialize(null);
                    }
                }
        );
        // 重新显示所有赛事
        String boatType = boatTypeComboBox1.getSelectionModel().getSelectedItem();
        athleteList.setAll(teamInfoService.showAthletesByBoatType(BoatTypeEnum.fromDisplayName(boatType)));
        athleteTable.refresh();
    }

    // 修改赛事事件
    private void handleModifyEvent(TeamVO team, AthleteVO athlete) {
        // 进行修改赛事操作
        if (team != null) {
            log.info("修改队伍: {}", team.getName());
            NavigationUtil.showPopup(
                    NavigationUtil.viewMap.get(addCKTeamButton.getId()),
                    "修改队伍",
                    teamTable.getScene().getWindow(),
                    controller -> {
                        if (controller instanceof UpdateCKTeamController) {
                            ((UpdateCKTeamController) controller).initialize(team);
                        }
                    }
            );
            // 重新显示所有赛事
            teamList.setAll(teamInfoService.showTeamsByEventId(searchField.getSelectionModel().getSelectedItem().getId()));
            teamTable.refresh();
        } else {
            log.info("修改选手: {}", athlete.getName());
            NavigationUtil.showPopup(
                    NavigationUtil.viewMap.get(addCKAthleteButton.getId()),
                    "修改信息",
                    teamTable.getScene().getWindow(),
                    controller -> {
                        if (controller instanceof UpdateCKAthleteController) {
                            ((UpdateCKAthleteController) controller).initialize(athlete);
                        }
                    }
            );
            // 重新显示所有赛事
            String boatType = boatTypeComboBox1.getSelectionModel().getSelectedItem();
            athleteList.setAll(teamInfoService.showAthletesByBoatType(BoatTypeEnum.fromDisplayName(boatType)));
            athleteTable.refresh();
        }
    }

    // 删除赛事事件
    private void handleDeleteEvent(TeamVO team, AthleteVO athlete) {
        Optional<ButtonType> result = showConfirmationDialog();
        // 删除赛事操作
        if (team != null) {
            if (result.isPresent() && Objects.equals(result.get().getText(), "确定")) {
                teamInfoService.deleteTeam(team.getId());
                log.info("删除队伍: {}", team.getName());
                // 刷新展示内容
                teamList.setAll(teamInfoService.showTeamsByEventId(searchField.getSelectionModel().getSelectedItem().getId()));
                teamTable.refresh();
                String boatType = boatTypeComboBox1.getSelectionModel().getSelectedItem();
                athleteList.setAll(teamInfoService.showAthletesByBoatType(BoatTypeEnum.fromDisplayName(boatType)));
                athleteTable.refresh();
            } else {
                log.info("取消删除");
            }
        } else {
            if (result.isPresent() && Objects.equals(result.get().getText(), "确定")) {
                teamInfoService.deleteAthlete(athlete.getId());
                log.info("删除选手: {}", athlete.getName());
                // 刷新展示内容
                String boatType = boatTypeComboBox1.getSelectionModel().getSelectedItem();
                athleteList.setAll(teamInfoService.showAthletesByBoatType(BoatTypeEnum.fromDisplayName(boatType)));
                athleteTable.refresh();
            } else {
                log.info("取消删除");
            }
        }
    }

    // 对皮划艇菜单点击的处理
    @FXML
    public void handleRowingClick(ActionEvent event) throws Exception {
        log.info("切换到赛艇界面");
        NavigationUtil.navigateToScene(
                (Stage) sideNav.getScene().getWindow(),
                "/fxml/rowingViews/EventInfoView.fxml",
                "赛艇管理");
    }

    @FXML
    public void handleSearchTeam() {
        EventVO eventVO = searchField.getSelectionModel().getSelectedItem();
        String teamQuery = searchTextField1.getText().trim();  // 获取输入的队伍名称

        log.info("搜索栏内容为：{}", teamQuery);

        Team team = new Team();
        team.setEventId(eventVO.getId());
        if (!teamQuery.isEmpty()) {
            team.setName(teamQuery);
        }

        // 将过滤后的列表更新到表格
        teamList.setAll(teamInfoService.showSearchedTeams(team));
        teamTable.refresh();
    }

    @FXML
    public void handleSearchAthlete() {
        String boatType = boatTypeComboBox1.getSelectionModel().getSelectedItem();
        String nameQuery = searchTextField4.getText().trim();  // 获取输入的姓名
        String athleteTeamQuery = searchTextField5.getText().trim();  // 获取输入的队伍名称

        log.info("搜索栏内容为：{} {}", nameQuery, athleteTeamQuery);

        AthleteVO athleteVO = new AthleteVO();
        athleteVO.setBoatTypeEnum(BoatTypeEnum.fromDisplayName(boatType));
        if (!nameQuery.isEmpty()) {
            athleteVO.setName(nameQuery);
        }
        if (!athleteTeamQuery.isEmpty()) {
            athleteVO.setTeamName(athleteTeamQuery);
        }

        // 将过滤后的列表更新到表格
        athleteList.setAll(teamInfoService.showSearchedAthletes(athleteVO));
        athleteTable.refresh();
    }

    @FXML
    public void handleClearSearchTeam() {
        // 清空搜索框内容
        searchTextField1.clear();
        EventVO eventVO = searchField.getSelectionModel().getSelectedItem();

        // 重新显示所有赛事
        teamList.setAll(teamInfoService.showTeamsByEventId(eventVO.getId()));
        teamTable.refresh();
    }

    @FXML
    public void handleClearSearchAthlete() {
        // 清空搜索框内容
        searchTextField4.clear();
        searchTextField5.clear();

        // 重新显示所有赛事
        String boatType = boatTypeComboBox1.getSelectionModel().getSelectedItem();
        athleteList.setAll(teamInfoService.showAthletesByBoatType(BoatTypeEnum.fromDisplayName(boatType)));
        athleteTable.refresh();
    }

    @FXML
    private void handleImportTeams() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx", "*.xls"));
        File file = fileChooser.showOpenDialog(null);

        if (file != null) {
            try {
                teamInfoService.importTeams(file);
                teamList.setAll(teamInfoService.showTeamsByEventId(searchField.getSelectionModel().getSelectedItem().getId()));
                teamTable.refresh();
                importTeamStatusLabel.setText("批量导入成功！");
            } catch (Exception e) {
                log.info("导入数据出现异常：{}", e.getMessage());
                importTeamStatusLabel.setText("导入失败，请检查文件格式！");
            }
        }
    }

    @FXML
    private void handleImportAthletes() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx", "*.xls"));
        File file = fileChooser.showOpenDialog(null);

        if (file != null) {
            try {
                teamInfoService.importAthletes(file);
                String boatType = boatTypeComboBox1.getSelectionModel().getSelectedItem();
                athleteList.setAll(teamInfoService.showAthletesByBoatType(BoatTypeEnum.fromDisplayName(boatType)));
                athleteTable.refresh();
                importAthleteStatusLabel.setText("批量导入成功！");
            } catch (Exception e) {
                log.info("导入数据出现异常：{}", e.getMessage());
                importAthleteStatusLabel.setText("导入失败，请检查文件格式！");
            }
        }
    }
}
